<template>
  <BaseForm v-model="formDataModel" @close="$emit('callBack')" />

</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import DrillExamInfoApi from '/@/api/webPath/DrillExamInfoApi.ts';
import { translate } from "/@/i18n";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
import DrillInfoApi from '~/src/api/webPath/DrillInfoApi';
import { useSysDicList } from '~/src/utils/useSysDicList';
import dayjs from 'dayjs';
import SysDataApi from '~/src/api/webPath/sysDataApi';
defineOptions({
  name: 'DrillExamInfoEdit',
})
const props = defineProps({
  modelValue: {

  }
})
const emit = defineEmits(['fetch-data', 'callBack'])

const formRef = ref<FormInstance>();
const title = ref<string>('');
// 当前培训名称
let drillName = ""
const dialogFormVisible = ref<boolean>(false);
const drillInfoList = ref([])
const examTypeList = ref([])

onMounted(async () => {
  const data = (await DrillInfoApi.getFilteredPageData({})).data.records
  console.log("drillinfo exam data", data)
  drillInfoList.value = data.map(x => ({ value: x.id, label: x.drillName, type: x.type }))
})

function calcTotalScore(handlers, row){
  const singleNum = +(row["singleNum"] ?? 0)
  const singleScore = +(row["singleScore"] ?? 0)
  const multiNum = +(row["multiNum"] ?? 0)
  const multiScore = +(row["multiScore"] ?? 0)
  const judgeNum = +(row["judgeNum"] ?? 0)
  const judgeScore = +(row["judgeScore"] ?? 0)
  
  handlers.updateParam("examTotalScore",(singleNum * singleScore) + (multiNum * multiScore) + (judgeNum * judgeScore))
}


const formDataModel = ref({
  columnCount: 2,
  expandLimit: 6,
  autoFit: false,
  columnWidth: '300px',
  labelPosition: 'right',
  labelWidth: '150px',
  modelData: {},  //表单参数值 初始化
  callback: async (any: object) => {  //表单执行成功后回调

    const { data } = await DrillExamInfoApi.examSavePreview(JSON.stringify(any))
    console.log("exam preview data", data)
    const obj = {
      ...any,
      dataList: data
    }
    //完成数据提交
    const { message } = await DrillExamInfoApi.save(JSON.stringify(obj))
    $baseMessage(message, 'success', 'vab-hey-message-success');
    dialogFormVisible.value = false


    //事件及数据推送到上一层父类
    emit('callBack', any); //把表单数据推送到上一层
  },
  items: [  //表单item数据初始化
    {
      divider: "考试基本信息设置"
    },
    {
      label: "关联培训",
      field: "drillId",
      clearable: true,
      type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
      options: drillInfoList,
      callback: async (handlers, value, row)=>{
        handlers.updateParam("examType","")
        const drill = drillInfoList.value.find(x=>x.value == value)
        const res = await SysDataApi.getPageData({ type: 'drill_type', pid: drill?.type });
        res && (examTypeList.value = res.data.map(x=>({label: x.name, value: x.id})))
        drillName = drillInfoList.value.find(x=>x.value === value)?.label ?? ""
        if (row["startTime"]) {
          const startDate = dayjs(row["startTime"]).format("YYYY年MM月DD日")
          handlers.updateParam("examName", `${drillName}-${startDate}-考试`)
        } else {
          handlers.updateParam("examName", `${drillName}-考试`)
        }
      },
      expandColumn: true,

      placeholder: "请输入",

      rule:
      {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },

    },
    {
      label: "考试名称",
      field: "examName",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      expandColumn: true,

      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入考试名称"
      }
      ]

    },
    {
      label: "考试时间（分钟）",
      field: "examDuration",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,

      placeholder: "请输入",
      callback(handlers, formData, v) {
        console.log("handlers", handlers, "formData", formData, "v", v)
        if (formData.startTime) {
          handlers.updateParam("endTime", dayjs(formData.satrtTime).add(+v, 'minute').format("YYYY-MM-DD HH:mm:ss"))
        }
      },
      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入考试时间"
      }
      ]

    },
    {
      label: "考试总分（分）",
      field: "examTotalScore",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      config: {
        disabled: true,
      },

      placeholder: "系统自动计算",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入考试总分"
      }
      ]

    },
    {
      label: "考试类型",
      field: "examType",
      clearable: true,
      type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
      options: examTypeList,

      placeholder: "请输入",

      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },

    },
    {
      label: "通过分（分）",
      field: "passScore",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,

      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入通过分"
      }
      ]

    },
    {
      label: "考试开始时间",
      field: "startTime",
      clearable: true,
      type: FORM_FIELD_TYPE.DATETIME,
      placeholder: "早于这个时间无法扫码",
      callback(handlers, formData, v) {
        console.log("handlers", handlers, "formData", formData, "v", v)
        const startDate = dayjs(v).format("YYYY年MM月DD日")
        const examName = formData.examName
        if (examName) {
          if (examName.includes("-")) {
            const currExamName = examName.split("-")[0]
            handlers.updateParam("examName",`${currExamName}-${startDate}-考试`)
          } else {
            handlers.updateParam("examName",`${drillName}-${startDate}-考试`)
          }
        }
        if (formData.examDuration) {
          handlers.updateParam("endTime", dayjs(v).add(+formData.examDuration, 'minute').format("YYYY-MM-DD HH:mm:ss"))
        }
      },
      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入考试开始时间"
      }
      ],

      config: {
        props: {   //日期精度配置
          type: "daterange",
          startPlaceholder: "开始日期",
          endPlaceholder: "结束日期",
          format: "YYYY-MM-DD",
        }
      },
    },
    {
      label: "考试结束时间",
      field: "endTime",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      placeholder: "系统自动计算",

      config: {
        props: {
          type: "datetime",
          format: "YYYY-MM-DD HH:mm:ss",
        },
        disabled: true,

      },
      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },

      ],


    },
    {
      divider: "题型设置（要求小于导入的数量）"
    },
    {
      label: "单选数量",
      field: "singleNum",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUTNUMBER,
      callback(handlers, form) {
        calcTotalScore(handlers, form)
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入单选数量"
      }
      ],

    },
    {
      label: "每题分值",
      field: "singleScore",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      callback(handlers, form) {
        calcTotalScore(handlers, form)
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入每题分值"
      }
      ],

    },
    {
      label: "不定项选择题数量",
      field: "multiNum",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUTNUMBER,
      callback(handlers, form) {
        calcTotalScore(handlers, form)
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入不定项选择题数量"
      }
      ],

    },
    {
      label: "每题分值",
      field: "multiScore",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      callback(handlers, form) {
        calcTotalScore(handlers, form)
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入每题分值"
      }
      ],

    },
    {
      label: "判断数量",
      field: "judgeNum",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUTNUMBER,
      callback(handlers, form) {
        calcTotalScore(handlers, form)
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入判断数量"
      }
      ],

    },
    {
      label: "每题分值",
      field: "judgeScore",
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      callback(handlers, form) {
        calcTotalScore(handlers, form)
      },
      placeholder: "请输入",

      rule: [{
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      {
        required: true,
        message: "请输入每题分值"
      }
      ],

    },
    //   {
    //     label: "创建人",
    //     field: "creator",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    //   {
    //     label: "修改人",
    //     field: "reviser",
    //     clearable: true,
    //     type: FORM_FIELD_TYPE.INPUT,

    //    placeholder:"请输入",

    //    rule:{
    //      trigger: 'blur',
    //      validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //            callback();
    //        },
    //      },

    // },
    // {
    //   label: "排序",
    //   field: "sort",
    //   clearable: true,
    //   type: FORM_FIELD_TYPE.INPUTNUMBER,
    //   defaultValue: 0,

    //   placeholder: "请输入",

    //   rule: {
    //     trigger: 'blur',
    //     validator: (rule: any, value: any, callback: any) => {  //绑定验证
    //       callback();
    //     },
    //   },

    // },

  ],
})






//页面数据加载
onMounted(async () => {

  //初始化数据model
  if (props.modelValue.query) { //跳转过来时候有参数
    if (props.modelValue.query.drillExamInfoId) {  //id存在则为编辑，加载网络数据，如上级页面带参数手动覆盖

      const { data } = await DrillExamInfoApi.getDetail({
        drillExamInfoId: props.modelValue.query.drillExamInfoId   //从路由中获取参数
      })
      drillName = data.drillName
      formDataModel.value.modelData = data;
    } else {
      //新增时候则用父类页面传参默认填充可根据业务修改
      for (const key in props.modelValue.query) {
        formDataModel.value.modelData[key] = props.modelValue.query[key]
      }
    }
  }
})


//方法暴露区域  todo
defineExpose({

})

</script>
